package com.study.operateDB.interfa.impl;

import java.util.List;
import java.util.Map;

import com.study.operateDB.interfa.SQLResult;
import com.study.operateDB.sql.PreparedSQL;

public class BaseSQLResult implements SQLResult {

	private final PreparedSQL preparedSQL;
	private String[] columnNames;
	private List<Object[]> rows;

	private int rowCount;
	private int columnCount;

	public BaseSQLResult(PreparedSQL preparedSQL) {
		this.preparedSQL = preparedSQL;
	}

	public String[] getColumnNames() {
		return columnNames;
	}

	public void setColumnNames(String[] columnNames) {
		this.columnNames = columnNames;
	}

	public List<Object[]> getRows() {
		return rows;
	}

	public void setRows(List<Object[]> rows) {
		this.rows = rows;
	}

	public int getRowCount() {
		return rowCount;
	}

	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
	}

	public int getColumnCount() {
		return columnCount;
	}

	public void setColumnCount(int columnCount) {
		this.columnCount = columnCount;
	}

	public PreparedSQL getPreparedSQL() {
		return preparedSQL;
	}

	@Override
	public String getSql() {
		return this.preparedSQL.getSql();
	}

	@Override
	public Object[] getParams() {
		return this.preparedSQL.getParams();
	}

	@Override
	public Map<String, String> getMetas() {

		return this.preparedSQL.getMeta();
	}

	@Override
	public boolean isRowsEmpty() {

		return rows.isEmpty();

	}

	@Override
	public <T> T getColumnValue(int columnIndex, int rowIndex, Class<T> clazz) {
		if (columnIndex >= columnCount || rowIndex >= rowCount) {
			throw new IllegalArgumentException("Doesn't exist Column Index ["
					+ columnIndex + "], Row Index [" + rowIndex + "]");
		}

		return (T) rows.get(rowIndex)[columnIndex];
	}

	@Override
	public <T> T getColumnValue(String columnName, int rowIndex, Class<T> clazz) {
		int columnIndex = this.getColumnIndex(columnName);
		return this.getColumnValue(columnIndex, rowIndex, clazz);
	}

	@Override
	public <T> T[] getColumnValues(int columnIndex, T[] array) {
		if (columnIndex >= columnCount) {
			throw new IllegalArgumentException("Doesn't exist Column Index ["
					+ columnIndex + "]");
		}

		int row = 0;
		for (Object[] innerResult : rows) {
			array[row++] = (T) innerResult[columnIndex];
		}

		return array;
	}

	@Override
	public <T> T[] getColumnValues(String columnName, T[] array) {
		int columnIndex = this.getColumnIndex(columnName);
		return this.getColumnValues(columnIndex, array);
	}

	@Override
	public int getColumnIndex(String columnName) {
		for (int index = 0; index < columnNames.length; index++) {
			if (columnNames[index].equalsIgnoreCase(columnName)) {
				return index;
			}
		}

		throw new IllegalArgumentException("Doesn't exist Column ["
				+ columnName + "]");
	}

}
